package com.codewsq.java.executors;


import java.util.concurrent.*;

class MyRunnable implements Runnable {

    @Override
    public void run() {
        Thread.currentThread().setName("Runnable线程");
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

class MyCallable implements Callable<Integer> {

    @Override
    public Integer call() throws Exception { // 100以内的奇数之和，包含100
        int sum = 0;
        for (int i = 0; i <= 100; i++) {
            if (i % 2 != 0) {
                sum += i;
            }
        }
        return sum;
    }
}

public class ThreadPoolTest {
    public static void main(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(10);

        executorService.execute(new MyRunnable()); // 只适用于 Runnable 方式


//        executorService.submit(new MyRunnable());
        Future<Integer> future = executorService.submit(new MyCallable()); // submit()既适用于Runnable，也适用于Callable
        try {
            Integer sum = future.get();
            System.out.println("submit方式运行Callable线程的返回结果：" + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        executorService.shutdown();


        /*--------------------------------管理线程池，设置线程池属性---------------------------------------*/
        ExecutorService service = Executors.newFixedThreadPool(10);
        System.out.println(service.getClass());
        ThreadPoolExecutor threadPool = (ThreadPoolExecutor) service;
        threadPool.setCorePoolSize(10); // 核心池大小
        threadPool.setMaximumPoolSize(15); // 最大线程数
        threadPool.setKeepAliveTime(5000, TimeUnit.MILLISECONDS); // 线程没有任务时最多保持多长时间会终止
    }
}
